//
//  YWTroubleMissionCell.m
//  maintain
//
//  Created by 郑想 on 16/7/28.
//  Copyright © 2016年 ewin. All rights reserved.
//
#import <SDWebImage/UIImageView+WebCache.h>
#import "YWMission.h"
#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWCommonTool.h"
#import "YWHandler.h"
#import "YWLoginTool.h"
#import "YWMacro.h"
#import "Masonry.h"
#import "YWTroubleMissionCell.h"
#import "UIColor+CustomColors.h"
#import "YWAnimationView.h"
#import "YWBuildingManager.h"
#import "YWReportTroubleModel.h"
#import "YWLocation.h"
#import "YWTroubleMissionModel.h"
#import "YWEquipmentType.h"
#import "YYLabel.h"

#import "YWContactManager.h"
#import "YWReplyManager.h"
#import "YWReply.h"

@interface YWTroubleMissionCell()
/** 头像 */
@property (nonatomic, strong) UIImageView* headImageView;
/** 发布者 */
@property (nonatomic, strong) YYLabel* createrNameLabel;
/** 创建时间 */
@property (nonatomic, strong) YYLabel* createTimeLabel;
/** 编号 */
@property (nonatomic, strong) YYLabel *numberLabel;
/** 执行人 */
@property (nonatomic, strong) YYLabel* nameLabel;
/** 设备名 */
@property (nonatomic, strong) YYLabel* equipmentLabel;
/** 位置 */
@property (nonatomic, strong) YYLabel* locationLabel;
/** 截止时间 */
@property (nonatomic, strong) YYLabel* deadlineDateLabel;
/** 故障说明 */
@property (nonatomic, strong) YYLabel* noteLabel;
/** 要求 */
@property (nonatomic, strong) YYLabel* demandLabel;
/** 状态图 */
@property (nonatomic, strong) UIImageView * finishStateImage;
@end

@implementation YWTroubleMissionCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    YWTroubleMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMissionCellIdentifier];
    if (cell == nil) {
        cell = [[YWTroubleMissionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:YWTroubleMissionCellIdentifier];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.layer.shouldRasterize = YES;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
        [self setUpSubviews];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //self.separatorInset = UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
    }
    return self;
}

- (void)setTroubleMissionModel:(YWTroubleMissionModel *)troubleMissionModel{
    _troubleMissionModel = troubleMissionModel;
    
    //    创建者头像
    NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:_troubleMissionModel.creator.headIcon];
    [_headImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
    
    //    创建者
    _createrNameLabel.text = _troubleMissionModel.creator.userName ? :NSLocalizedString(@"none", nil);
    //    任务时间
    NSString *time = _troubleMissionModel.troubleStatus==YWTroubleMissionStatusFinish?  [YWCommonTool showTimeWithNormalFormatter:_troubleMissionModel.updateTime / 1000]? :NSLocalizedString(@"none", nil) : [YWCommonTool showTimeWithNormalFormatter:_troubleMissionModel.createTime / 1000]? :NSLocalizedString(@"none", nil);
    _createTimeLabel.text = time;
    //    编号
    NSString*troubleSequence = _troubleMissionModel.trouble.troubleSequence ?: @"";
    _numberLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"codeFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:troubleSequence secondColor:[UIColor customYellowColor] font:kContentFont];
    //    设备名
    NSString *equipmentName = nil;
    if (_troubleMissionModel.trouble.equipment) {
        equipmentName = _troubleMissionModel.trouble.equipment.equipmentName?:NSLocalizedString(@"none", nil);
    }else if (_troubleMissionModel.trouble.equipmentType){
        equipmentName = _troubleMissionModel.trouble.equipmentType.equipmentTypeName?:NSLocalizedString(@"none", nil);//[[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:_troubleMission.equipmentTypeId];
    }
    
    _equipmentLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"equipmentFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:equipmentName.length?equipmentName:NSLocalizedString(@"none", nil) secondColor:[UIColor blackColor] font:kContentFont];
    NSString *locationStr = @"";
    if (_troubleMissionModel.trouble.equipment.equipmentId.length) {
        YWEquipment* equipment = _troubleMissionModel.trouble.equipment;//[[YWEquipmentManager shareManager] equipmentWithId:_troubleMissionModel.trouble.equipment.equipmentId];
        locationStr = equipment ? [[YWBuildingManager shareManager] equipmentLocation:equipment] : nil;
    }
    if (locationStr.length==0 && _troubleMissionModel.trouble.location.locationId) {
        locationStr = [[YWBuildingManager shareManager] areaLocationWithLocationId:_troubleMissionModel.trouble.location.locationId];
    }
    
    //    执行者
    NSString*executorName =_troubleMissionModel.executor.userName ? :NSLocalizedString(@"none", nil);
    _nameLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"troubleExecutorFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:executorName secondColor:[UIColor customYellowColor] font:kContentFont];
    //    截止时间
    NSString*cutoffTime = [YWCommonTool showTime:_troubleMissionModel.cutoffTime / 1000 andFormatter:KTimeFormatFullDate] ? : NSLocalizedString(@"none", nil);
    _deadlineDateLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"deadlineFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:cutoffTime secondColor:[UIColor customYellowColor] font:kContentFont];
    //    故障说明
    NSString* noteText = _troubleMissionModel.trouble.note.length ? _troubleMissionModel.trouble.note:NSLocalizedString(@"noContent", nil);
    _noteLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"explainFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:noteText secondColor:[UIColor blackColor] font:kContentFont];
    //    任务要求
    NSString*demand = _troubleMissionModel.demand.length ? _troubleMissionModel.demand :NSLocalizedString(@"noContent", nil);
    _demandLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"demandFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:demand secondColor:[UIColor blackColor] font:kContentFont];
    //    位置
    _locationLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"locationFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:locationStr.length?locationStr:NSLocalizedString(@"none", nil) secondColor:[UIColor blackColor] font:kContentFont];
    //状态图类型
//    _finishStateLabel.type = YWAnimationViewTypeRectangle;
    if (_troubleMissionModel.troubleStatus == YWTroubleMissionStatusFinish) {
        [_finishStateImage setImage:[UIImage imageNamed:@"mission_newfinished"]];
//        [self setShowFinishState:YWAnimationViewShowStatusFinished];
    }
    else {
        [_finishStateImage setImage:nil];
//        [self setShowFinishState:YWAnimationViewShowStatusExpire];
    }
    
    NSInteger reporterId = _troubleMissionModel.trouble.reporter.uniqueId;
    NSInteger creatorId = _troubleMissionModel.creator.uniqueId;
    NSInteger executorId = _troubleMissionModel.executor.uniqueId;
    NSString * reporterName;
    NSString * creatorName;
    NSString * repairName;
    NSInteger showCount = 0;
    NSMutableArray *idMutArray = [NSMutableArray array];
    if (reporterId>0) {
        showCount++;
        reporterName = _troubleMissionModel.trouble.reporter.userName;
        [idMutArray addObject:@(reporterId)];
    }
    if (creatorId>0 && creatorId!=reporterId) {
        showCount++;
        creatorName = _troubleMissionModel.creator.userName;
        [idMutArray addObject:@(creatorId)];
    }
    if (executorId>0 && executorId!=reporterId && executorId!=creatorId) {
        showCount++;
        repairName = _troubleMissionModel.executor.userName;
        [idMutArray addObject:@(executorId)];
    }
    NSInteger observerCount = _troubleMissionModel.trouble.observers.count;
    NSMutableArray * observerMur = [NSMutableArray arrayWithArray:_troubleMissionModel.trouble.observers];//将参与者拿出来
    NSMutableArray * observerIds = [NSMutableArray array];
    [observerMur enumerateObjectsUsingBlock:^(YWHandler* _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        [observerIds addObject:@(handler.uniqueId)];
    }];
    if (observerCount) {
        for (id object in idMutArray) {
            NSInteger uniqueId = [object integerValue];
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
            NSArray *array = [[_troubleMissionModel.trouble.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
            if (array.count==1) {
                observerCount--;
                [observerIds removeObject:@(uniqueId)];
            }
            if (observerCount==0) {
                break;
            }
        }
        showCount = showCount + observerCount;
    }
    NSString * firstStr = [NSString stringWithFormat:@"%@(%ld): ",NSLocalizedString(@"observer", nil),(long)showCount];
    
    [observerMur removeAllObjects];
    NSMutableString *observerName = [[NSMutableString alloc] init];
    if (observerIds.count) {
        for (id obj in observerIds ) {
            NSInteger uniqueId = [obj integerValue];
            YWHandler *handler = [[YWContactManager shareManager] getHandlerWithUniqueId:uniqueId];
            [observerMur addObject:handler];
        }
    }
    [observerMur enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (observerName.length && idx!=0) {
            [observerName appendString:@"   "];
        }
        [observerName appendString:handler.userName];
    }];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@ %@ %@ %@",reporterName?:@"",creatorName?:@"",repairName?:@"",observerName?:@""];//参与者要加进来
    
    self.observersLabel.attributedText = [YWCommonTool attributedTextWithFirstText:firstStr firstColor:[UIColor customTextGrayBlackColor] secondText:nameStr secondColor:[UIColor customBlueColor] font:kContentFont];
    //评论，如果没有评论，那么要重新设置约束
    //有评论
    NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:_troubleMissionModel.trouble.troubleId andRelationType:YWReplyRelationTypeTrouble];
    if (commentArray.count>0) {
        YWReply * reply = [commentArray firstObject];
        NSString * replyCount = [NSString stringWithFormat:@"%@(%ld): ",NSLocalizedString(@"comment", nil),commentArray.count];
        //    时间
        NSString * timeStr = [YWCommonTool recordDateByFormatTimeString:reply.replyTime/1000 showYear:YES];
        NSString * timeText = [NSString stringWithFormat:@"  %@",timeStr];
        //    内容
        NSString *replyName = [NSString stringWithFormat:@"%@: ",reply.replier.userName];
        NSString *atUserName = reply.atUser.userName.length>0?[NSString stringWithFormat:@" @%@",reply.atUser.userName]:@"";
        NSString * content = atUserName.length?[NSString stringWithFormat:@" %@  ",reply.content.length>0?reply.content:@""] : (reply.content.length>0?reply.content:@"");
        
        self.replyLabel.attributedText = [YWCommonTool attributedTextWithFirstText:replyCount firstColor:[UIColor customTextGrayColor] firstFont:kContentFont secondText:replyName secondColor:[UIColor customBlueColor] secFont:kContentFont thirdText:atUserName thirdColor:[UIColor customBlueColor] thirdFont:kContentFont fourthText:content fourthColor:[UIColor blackColor] fourFont:kContentFont fifthText:timeText fifthColor:[UIColor customTextGrayColor] fifthFont:[UIFont systemFontOfSize:13]];
    }else{
        self.replyLabel.attributedText = nil;
    }
    self.noteLabel.preferredMaxLayoutWidth = self.noteLabel.frame.size.width;
    self.equipmentLabel.preferredMaxLayoutWidth = self.equipmentLabel.frame.size.width;
    self.locationLabel.preferredMaxLayoutWidth = self.locationLabel.frame.size.width;
    self.nameLabel.preferredMaxLayoutWidth = self.nameLabel.frame.size.width;
    self.demandLabel.preferredMaxLayoutWidth = self.demandLabel.frame.size.width;
}

//- (YWAnimationView*)finishStateLabel
//{
//    if (!_finishStateLabel) {
//        YWAnimationView* finishStateLabel = [YWAnimationView animationView];
//        finishStateLabel.opaque = YES;
//        finishStateLabel.type = YWAnimationViewTypeRectangle;
//        [self.contentView addSubview:finishStateLabel];
//        _finishStateLabel = finishStateLabel;
//    }
//    return _finishStateLabel;
//}

- (UIImageView*)finishStateImage{
    if (!_finishStateImage) {
        UIImageView *imageView = [UIImageView new];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 32;
        _finishStateImage = imageView;
        [self.contentView addSubview:_finishStateImage];
    }
    return _finishStateImage;
}

//- (void)setShowFinishState:(YWAnimationViewShowStatus)animationViewShowStatus
//{
//    self.finishStateLabel.showStatus = animationViewShowStatus;
//}

//+ (NSString*)requestWithMission:(YWTroubleMission*)troubleMission
//{
//    return [NSString stringWithFormat:@"要求：%@", troubleMission.demand.length ? troubleMission.demand : @"未填写"];
//    
//    //   return [NSString stringWithFormat:@"要求：%@", mission.demand];
//}
//
//+ (NSString*)noteWithMission:(YWTroubleMission*)troubleMission
//{
//    return [NSString stringWithFormat:@"%@", troubleMission.note.length ? troubleMission.note : @"未填写"];
//}


- (void)setUpSubviews {
    UIView *superview = self.contentView;
    /**
     *  头像 名字
     *  头像 时间
     */
    [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.mas_equalTo(superview).offset(8);
        make.width.and.height.mas_equalTo(@46);
    }];
    
    [self.createrNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(_headImageView.mas_centerY).offset(-2);
        make.left.mas_equalTo(_headImageView.mas_right).offset(6);
    }];
    
    [self.createTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_createrNameLabel);
        make.top.mas_equalTo(_createrNameLabel.mas_bottom).offset(4);
    }];
    /**
     *  编号
     *  巡查人
     *  位置
     *  路线
     *  要求
     *  巡查日
     */
    
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_headImageView.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_numberLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-72);
    }];
    
    [self.equipmentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_nameLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-72);
        
    }];
    
    [self.locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_equipmentLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-72);
    }];
    
    [self.deadlineDateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_locationLabel.mas_bottom).offset(6);
    }];
    
    [self.noteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_deadlineDateLabel.mas_bottom).offset(6);
    }];
    
    [self.demandLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_noteLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(@[_numberLabel, _deadlineDateLabel, _noteLabel]);
//        make.bottom.mas_equalTo(superview).offset(-6);
    }];
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_demandLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(superview);
        make.height.mas_equalTo(@1.0);
    }];
    
    [self.observersLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.separatorLineView.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_demandLabel);
    }];
    [self.replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.observersLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_demandLabel);
        make.bottom.mas_equalTo(superview).offset(-6);
    }];
//    [self.finishStateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(_demandLabel.mas_bottom);
//        make.right.and.bottom.mas_equalTo(superview);
//        make.size.mas_equalTo(CGSizeMake(70, 20));
//    }];
    [self.finishStateImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_nameLabel);
        make.right.mas_equalTo(superview).offset(-8);
        make.size.mas_equalTo(CGSizeMake(64, 64));
    }];
}

//- (void)layoutSubviews{
//    [super layoutSubviews];
//    
//}

- (UIImageView *)headImageView{
    if (!_headImageView) {
        UIImageView *imageView = [UIImageView new];
        imageView.clipsToBounds = YES;
        imageView.layer.cornerRadius = 46/2;
        _headImageView = imageView;
        [self.contentView addSubview:_headImageView];
    }
    return _headImageView;
}

- (YYLabel *)createrNameLabel{
    if (!_createrNameLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor blackColor];
        _createrNameLabel = label;
        [self.contentView addSubview:_createrNameLabel];
    }
    return _createrNameLabel;
}

- (YYLabel *)createTimeLabel{
    if (!_createTimeLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _createTimeLabel = label;
        [self.contentView addSubview:_createTimeLabel];
    }
    return _createTimeLabel;
}

- (YYLabel *)numberLabel{
    if (!_numberLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        _numberLabel = label;
        [self.contentView addSubview:_numberLabel];
    }
    return _numberLabel;
}

- (YYLabel *)nameLabel{
    if (!_nameLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _nameLabel = label;
        [self.contentView addSubview:_nameLabel];
    }
    return _nameLabel;
}

- (YYLabel *)equipmentLabel{
    if (!_equipmentLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _equipmentLabel = label;
        [self.contentView addSubview:_equipmentLabel];
    }
    return _equipmentLabel;
}

- (YYLabel *)locationLabel{
    if (!_locationLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _locationLabel = label;
        [self.contentView addSubview:_locationLabel];
    }
    return _locationLabel;
}

- (YYLabel *)deadlineDateLabel{
    if (!_deadlineDateLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        _deadlineDateLabel = label;
        [self.contentView addSubview:_deadlineDateLabel];
    }
    return _deadlineDateLabel;
}

- (YYLabel *)noteLabel{
    if (!_noteLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _noteLabel = label;
        [self.contentView addSubview:_noteLabel];
    }
    return _noteLabel;
}

- (YYLabel *)demandLabel{
    if (!_demandLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _demandLabel = label;
        [self.contentView addSubview:_demandLabel];
    }
    return _demandLabel;
}

@end
